const jwt = require('jsonwebtoken');
const config = require('../config/config');
const { formatResponse } = require('../utils/transform');

// 简单的Bearer Token校验中间件
const requireAuth = async function requireAuth(ctx, next) {
  try {
    const authHeader = ctx.request.headers['authorization'] || ctx.request.headers['Authorization'];
    if (!authHeader) {
      ctx.status = 401;
      ctx.body = formatResponse(401, '未授权，缺少令牌', null);
      return;
    }

    const parts = String(authHeader).split(' ');
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
      ctx.status = 401;
      ctx.body = formatResponse(401, '未授权，令牌格式错误', null);
      return;
    }

    const token = parts[1];
    try {
      const decoded = jwt.verify(token, config.jwt.secret);
      // 将用户信息放到state，供后续处理使用
      ctx.state.user = decoded;
    } catch (e) {
      ctx.status = 401;
      ctx.body = formatResponse(401, '未授权或令牌无效', null);
      return;
    }

    await next();
  } catch (error) {
    console.error('认证中间件错误:', error);
    ctx.status = 500;
    ctx.body = formatResponse(500, '认证失败', null, { error: error.message });
  }
};

module.exports = requireAuth;
module.exports.requireScope = function(requiredScopes = []) {
  return async function scopeCheck(ctx, next) {
    try {
      const user = ctx.state.user;
      if (!user) {
        ctx.status = 401;
        ctx.body = formatResponse(401, '未授权，缺少令牌', null);
        return;
      }
      const scopes = Array.isArray(user.scope)
        ? user.scope
        : (user.scope ? String(user.scope).split(/\s+/) : (user.type === 1 ? ['read','write'] : ['read']));
      const needed = Array.isArray(requiredScopes) ? requiredScopes : [requiredScopes];
      const ok = needed.every(s => scopes.includes(s));
      if (!ok) {
        ctx.status = 403;
        ctx.body = formatResponse(403, '权限不足，缺少必要的scope', { required: needed, current: scopes });
        return;
      }
      await next();
    } catch (error) {
      console.error('Scope权限校验错误:', error);
      ctx.status = 500;
      ctx.body = formatResponse(500, '权限校验失败', null, { error: error.message });
    }
  };
};